import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { StorehouseService, Warehouse, WarehouseWithLocations } from './storehouse.service';
import { ToasterService } from '@abp/ng.theme.shared';
import { StorehouseFormComponent } from './storehouse-form/storehouse-form.component';
import { StorehouseDetailComponent } from './storehouse-detail/storehouse-detail.component';
import { finalize } from 'rxjs/operators';
import { ConfigStateService } from '@abp/ng.core';

@Component({
  selector: 'app-storehouse',
  template: `
    <div class="page-container">
      <!-- 搜索区域 -->
      <div class="search-area">
        <div class="search-form">
          <div class="form-item">
            <span>仓库：</span>
            <input type="text" placeholder="请输入仓库名称/编号" [(ngModel)]="searchParams.warehouseCode">
          </div>
          <div class="form-item">
            <span>仓库状态：</span>
            <select [(ngModel)]="searchParams.warehouseStatus">
              <option value="">请选择</option>
              <option value="启用">启用</option>
              <option value="停用">停用</option>
              <option value="已锁定">已锁定</option>
            </select>
          </div>
          <div class="form-item">
            <span>库管部门：</span>
            <input type="text" placeholder="请输入" [(ngModel)]="searchParams.managementDept">
          </div>
          <div class="form-item">
            <span>仓库主管：</span>
            <input type="text" placeholder="请输入" [(ngModel)]="searchParams.warehouseManager">
          </div>
          <div class="form-buttons">
            <button type="button" class="btn-reset" (click)="reset()">
              <i class="fas fa-undo"></i>
              重置
            </button>
            <button type="button" class="btn-search" (click)="search()">
              <i class="fas fa-search"></i>
              查询
            </button>
            <button type="button" class="btn-advanced" (click)="toggleAdvancedSearch()">
              <i class="fas fa-sliders"></i>
              高级搜索
            </button>
          </div>
        </div>
      </div>

      <!-- 操作按钮区域 -->
      <div class="operation-area">
        <button type="button" class="btn-add" (click)="addWarehouse()">
          <i class="fas fa-plus"></i>
          新增
        </button>
        <button type="button" class="btn-delete" (click)="deleteSelected()">
          <i class="fas fa-trash"></i>
          删除
        </button>
        <button type="button" class="btn-enable" (click)="enableSelected($event)">
          <i class="fas fa-play"></i>
          启用
        </button>
        <button type="button" class="btn-disable" (click)="disableSelected($event)">
          <i class="fas fa-stop"></i>
          停用
        </button>
        <button type="button" class="btn-lock" (click)="lockSelected($event)">
          <i class="fas fa-lock"></i>
          锁定
        </button>
      </div>

      <!-- 表格区域 -->
      <div class="table-container">
        <div *ngIf="loading" class="loading-overlay">
          <div class="loading-spinner"></div>
          <span>加载中...</span>
        </div>
        <table>
          <thead>
            <tr>
              <th>
                <input type="checkbox" 
                       [checked]="isAllSelected()" 
                       (change)="toggleSelectAll()">
              </th>
              <th>序号</th>
              <th>仓库编号</th>
              <th>仓库名称</th>
              <th>仓库容量</th>
              <th>仓库地址</th>
              <th>库管部门</th>
              <th>仓库主管</th>
              <th>库位数量</th>
              <th>仓库状态</th>
              <th>操作人</th>
              <th>操作时间</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr *ngFor="let item of warehouseList; let i = index">
              <td>
                <input type="checkbox" 
                       [checked]="isSelected(item.id)"
                       (change)="toggleSelect(item.id)">
              </td>
              <td>{{i + 1}}</td>
              <td>{{item.warehouseCode}}</td>
              <td>{{item.warehouseName}}</td>
              <td>{{item.warehouseCapacity}}</td>
              <td>{{item.warehouseAddress}}</td>
              <td>{{item.managementDept}}</td>
              <td>{{item.warehouseManager}}</td>
              <td>{{item.locationCount}}</td>
              <td>
                <span [ngClass]="{
                  'status-enabled': item.warehouseStatus === '启用',
                  'status-disabled': item.warehouseStatus === '停用',
                  'status-locked': item.warehouseStatus === '锁定'
                }">
                  {{item.warehouseStatus || '-'}}
                </span>
              </td>
              <td>{{getUserName(item.creatorId)}}</td>
              <td>{{item.creationTime | date:'yyyy-MM-dd HH:mm:ss' || '-'}}</td>
              <td class="operation-column">

              <a class="btn-view" (click)="viewWarehouseDetails(item)">
                  <i class="fas fa-eye"></i>
                  详情
                </a>
                
                <a class="btn-edit" (click)="editWarehouse(item)">
                  <i class="fas fa-edit"></i>
                  编辑
                </a>
                
                <a class="btn-delete" (click)="deleteWarehouse(item.id)">
                  <i class="fas fa-trash"></i>
                  删除
                </a>
              </td>
            </tr>
          </tbody>
        </table>
      </div>

      <!-- 分页区域 -->
      <div class="pagination">
        <span>总 {{totalCount}} 条</span>
        <div class="page-numbers">
          <a *ngFor="let page of pages" 
             [class.active]="currentPage === page"
             (click)="goToPage(page)">{{page}}</a>
          <span *ngIf="hasMorePages">...</span>
          <a *ngIf="hasMorePages" 
             [class.active]="currentPage === totalPages"
             (click)="goToPage(totalPages)">{{totalPages}}</a>
        </div>
        <div class="page-size">
          <select [(ngModel)]="pageSize" (change)="onPageSizeChange()">
            <option [value]="10">10条/页</option>
            <option [value]="20">20条/页</option>
            <option [value]="50">50条/页</option>
          </select>
        </div>
      </div>

      <!-- Form Dialog -->
      <app-storehouse-form
        [visible]="showForm"
        [isEdit]="isEditing"
        [initialData]="editingWarehouse"
        (cancel)="hideForm()"
        (submit)="handleFormSubmit($event)"
      ></app-storehouse-form>

      <!-- 确认删除对话框 -->
      <div class="confirm-dialog-overlay" *ngIf="showDeleteConfirm">
        <div class="confirm-dialog">
          <div class="confirm-dialog-header">
            <i class="fas fa-exclamation-circle warning-icon"></i>
            <span>删除确认</span>
          </div>
          <div class="confirm-dialog-body">
            <p>{{ deletingWarehouseId ? '确定要删除这个仓库吗？' : '确定要删除选中的仓库吗？' }}</p>
            <p class="warning-text">此操作不可恢复！</p>
          </div>
          <div class="confirm-dialog-footer">
            <button class="btn-cancel" (click)="cancelDelete()">取消</button>
            <button class="btn-confirm" (click)="confirmDeleteSelected()">确定删除</button>
          </div>
        </div>
      </div>

      <!-- 高级查询侧边栏 -->
      <div class="advanced-search-sidebar" [class.show]="showAdvancedSearch">
        <div class="sidebar-header">
          <h3>高级搜索</h3>
          <button class="close-button" (click)="toggleAdvancedSearch()">×</button>
        </div>
        <div class="sidebar-body">
          <div class="form-group">
            <label>仓库编号</label>
            <input type="text" [(ngModel)]="advancedSearchParams.warehouseCode" placeholder="自动获取系统编号">
          </div>
          <div class="form-group">
            <label>仓库名称</label>
            <input type="text" [(ngModel)]="advancedSearchParams.warehouseName" placeholder="请输入">
          </div>
          <div class="form-group">
            <label>仓库容量</label>
            <div class="range-inputs">
              <input type="number" [(ngModel)]="advancedSearchParams.minCapacity" placeholder="请输入">
              <span>-</span>
              <input type="number" [(ngModel)]="advancedSearchParams.maxCapacity" placeholder="请输入">
            </div>
          </div>
          <div class="form-group">
            <label>库管部门</label>
            <input type="text" [(ngModel)]="advancedSearchParams.managementDept" placeholder="请输入">
          </div>
          <div class="form-group">
            <label>仓库主管</label>
            <input type="text" [(ngModel)]="advancedSearchParams.warehouseManager" placeholder="请输入">
          </div>
          <div class="form-group">
            <label>仓库地址</label>
            <input type="text" [(ngModel)]="advancedSearchParams.warehouseAddress" placeholder="请输入">
          </div>
          <div class="form-group">
            <label>仓库状态</label>
            <select [(ngModel)]="advancedSearchParams.warehouseStatus">
              <option value="">请选择</option>
              <option value="启用">启用</option>
              <option value="停用">停用</option>
              <option value="锁定">锁定</option>
            </select>
          </div>
          <div class="form-group">
            <label>库位数量</label>
            <div class="range-inputs">
              <input type="number" [(ngModel)]="advancedSearchParams.minLocationCount" placeholder="请输入">
              <span>-</span>
              <input type="number" [(ngModel)]="advancedSearchParams.maxLocationCount" placeholder="请输入">
            </div>
          </div>
          <div class="form-group">
            <label>操作人</label>
            <input type="text" [(ngModel)]="advancedSearchParams.operator" placeholder="请输入">
          </div>
          <div class="form-group">
            <label>操作时间</label>
            <div class="range-inputs">
              <input type="datetime-local" [(ngModel)]="advancedSearchParams.operationTimeStart">
              <span>-</span>
              <input type="datetime-local" [(ngModel)]="advancedSearchParams.operationTimeEnd">
            </div>
          </div>
        </div>
        <div class="sidebar-footer">
          <button class="btn-reset" (click)="resetAdvancedSearch()">重置</button>
          <button class="btn-cancel" (click)="toggleAdvancedSearch()">取消</button>
          <button class="btn-search" (click)="searchWithAdvanced()">查询</button>
        </div>
      </div>

      <!-- 遮罩层 -->
      <div class="sidebar-overlay" *ngIf="showAdvancedSearch" (click)="toggleAdvancedSearch()"></div>

      <!-- 详情查看对话框 -->
      <app-storehouse-detail
        *ngIf="showDetail"
        [visible]="showDetail"
        [warehouse]="viewingWarehouse"
        [locations]="viewingLocations"
        [userNames]="userNames"
        (visibleChange)="hideDetail()">
      </app-storehouse-detail>
    </div>
  `,
  styles: [`
    .page-container {
      padding: 20px;
      background-color: #f5f5f5;
      min-height: 100vh;
    }

    .search-area {
      background: #fff;
      padding: 24px;
      border-radius: 8px;
      margin-bottom: 16px;
      box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.03);
    }

    .search-form {
      display: flex;
      flex-wrap: wrap;
      gap: 16px;
      align-items: flex-start;
    }

    .form-item {
      display: flex;
      align-items: center;
    }

    .form-item span {
      min-width: 70px;
      margin-right: 8px;
      color: #606266;
      font-size: 14px;
    }

    .form-item input,
    .form-item select {
      width: 220px;
      height: 36px;
      border: 1px solid #dcdfe6;
      border-radius: 4px;
      padding: 0 12px;
      font-size: 14px;
      color: #606266;
      transition: all 0.3s;
    }

    .form-item input:focus,
    .form-item select:focus {
      border-color: #409eff;
      outline: none;
      box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
    }

    .form-buttons {
      display: flex;
      gap: 12px;
      margin-left: auto;
    }

    button {
      height: 36px;
      padding: 0 20px;
      border-radius: 4px;
      border: 1px solid #dcdfe6;
      cursor: pointer;
      font-size: 14px;
      display: flex;
      align-items: center;
      gap: 8px;
      transition: all 0.3s;
    }

    .btn-reset {
      background: #fff;
      color: #606266;
    }

    .btn-reset:hover {
      color: #409eff;
      border-color: #409eff;
      background-color: #ecf5ff;
    }

    .btn-search {
      background: #409eff;
      color: #fff;
      border: none;
    }

    .btn-search:hover {
      background: #66b1ff;
    }

    .operation-area {
      margin-bottom: 16px;
      display: flex;
      gap: 12px;
      padding: 16px 24px;
      background: #fff;
      border-radius: 8px;
      box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.03);
    }

    .btn-add {
      background: #409eff;
      color: #fff;
      border: none;
    }

    .btn-add:hover {
      background: #66b1ff;
    }

    .btn-delete {
      color: #f56c6c;
      border-color: #fbc4c4;
    }

    .btn-delete:hover {
      color: #fff;
      background-color: #f56c6c;
      border-color: #f56c6c;
    }

    .btn-enable {
      color: #67c23a;
      border-color: #c2e7b0;
    }

    .btn-enable:hover {
      color: #fff;
      background-color: #67c23a;
      border-color: #67c23a;
    }

    .btn-disable {
      color: #ff4d4f;
      border-color: #ffccc7;
      background-color: #fff2f0;
    }

    .btn-disable:hover {
      color: #fff;
      background-color: #ff4d4f;
      border-color: #ff4d4f;
    }

    .btn-lock {
      color: #fa8c16;
      border-color: #ffd591;
      background-color: #fff7e6;
    }

    .btn-lock:hover {
      color: #fff;
      background-color: #fa8c16;
      border-color: #fa8c16;
    }

    .table-container {
      background: #fff;
      border-radius: 8px;
      box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.03);
      overflow: hidden;
    }

    table {
      width: 100%;
      border-collapse: collapse;
    }

    th, td {
      padding: 16px;
      text-align: left;
      font-size: 14px;
      border-bottom: 1px solid #ebeef5;
    }

    th {
      background: #fafafa;
      color: #606266;
      font-weight: 500;
      white-space: nowrap;
    }

    td {
      color: #606266;
    }

    tbody tr:hover {
      background: #f5f7fa;
    }

    .operation-column {
      display: flex;
      gap: 8px;
    }

    .operation-column a {
      padding: 4px 8px;
      border-radius: 4px;
      cursor: pointer;
      font-size: 13px;
      display: flex;
      align-items: center;
      gap: 4px;
      text-decoration: none;
    }

    .operation-column .btn-edit {
      color: #409eff;
      background-color: #ecf5ff;
    }

    .operation-column .btn-edit:hover {
      background-color: #409eff;
      color: #fff;
    }

    .operation-column .btn-delete {
      color: #f56c6c;
      background-color: #fef0f0;
    }

    .operation-column .btn-delete:hover {
      background-color: #f56c6c;
      color: #fff;
    }

    .pagination {
      margin-top: 16px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 16px 24px;
      background: #fff;
      border-radius: 8px;
      box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.03);
    }

    .page-numbers {
      display: flex;
      gap: 4px;
      align-items: center;
    }

    .page-numbers a {
      min-width: 32px;
      height: 32px;
      line-height: 32px;
      text-align: center;
      border: 1px solid #dcdfe6;
      border-radius: 4px;
      cursor: pointer;
      color: #606266;
      transition: all 0.3s;
    }

    .page-numbers a:hover {
      color: #409eff;
      border-color: #409eff;
    }

    .page-numbers a.active {
      background-color: #409eff;
      border-color: #409eff;
      color: #fff;
    }

    .page-size select {
      height: 32px;
      border: 1px solid #dcdfe6;
      border-radius: 4px;
      padding: 0 28px 0 12px;
      font-size: 14px;
      color: #606266;
      cursor: pointer;
      transition: all 0.3s;
      appearance: none;
      background: #fff url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='%23606266'%3E%3Cpath d='M7 10l5 5 5-5z'/%3E%3C/svg%3E") no-repeat right 8px center;
      background-size: 16px;
    }

    .page-size select:focus {
      border-color: #409eff;
      outline: none;
    }

    .loading-overlay {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background: rgba(255, 255, 255, 0.8);
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      z-index: 1000;
    }

    .loading-spinner {
      width: 40px;
      height: 40px;
      border: 4px solid #f3f3f3;
      border-top: 4px solid #3498db;
      border-radius: 50%;
      animation: spin 1s linear infinite;
    }

    .status-enabled {
      display: inline-block;
      padding: 4px 12px;
      border-radius: 4px;
      font-size: 12px;
      line-height: 1.4;
      background-color: #f6ffed;
      border: 1px solid #b7eb8f;
      color: #52c41a;
    }

    .status-disabled {
      display: inline-block;
      padding: 4px 12px;
      border-radius: 4px;
      font-size: 12px;
      line-height: 1.4;
      background-color: #fff2f0;
      border: 1px solid #ffccc7;
      color: #ff4d4f;
    }

    .status-locked {
      display: inline-block;
      padding: 4px 12px;
      border-radius: 4px;
      font-size: 12px;
      line-height: 1.4;
      background-color: #fff7e6;
      border: 1px solid #ffd591;
      color: #fa8c16;
    }

    @keyframes spin {
      0% { transform: rotate(0deg); }
      100% { transform: rotate(360deg); }
    }

    .confirm-dialog-overlay {
      position: fixed;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background-color: rgba(0, 0, 0, 0.5);
      display: flex;
      justify-content: center;
      align-items: center;
      z-index: 1000;
    }

    .confirm-dialog {
      background: white;
      border-radius: 8px;
      width: 400px;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
      animation: dialog-fade-in 0.3s ease;
    }

    @keyframes dialog-fade-in {
      from {
        opacity: 0;
        transform: translateY(-20px);
      }
      to {
        opacity: 1;
        transform: translateY(0);
      }
    }

    .confirm-dialog-header {
      padding: 20px;
      border-bottom: 1px solid #f0f0f0;
      display: flex;
      align-items: center;
      gap: 8px;
    }

    .warning-icon {
      color: #ff4d4f;
      font-size: 20px;
    }

    .confirm-dialog-header span {
      font-size: 16px;
      font-weight: 500;
      color: #262626;
    }

    .confirm-dialog-body {
      padding: 24px 20px;
    }

    .confirm-dialog-body p {
      margin: 0;
      color: #595959;
    }

    .warning-text {
      margin-top: 8px !important;
      color: #ff4d4f !important;
      font-size: 13px;
    }

    .confirm-dialog-footer {
      padding: 16px 20px;
      border-top: 1px solid #f0f0f0;
      display: flex;
      justify-content: flex-end;
      gap: 12px;
    }

    .btn-cancel, .btn-confirm {
      padding: 8px 16px;
      border-radius: 4px;
      font-size: 14px;
      cursor: pointer;
      transition: all 0.3s;
    }

    .btn-cancel {
      border: 1px solid #d9d9d9;
      background: white;
      color: #595959;
    }

    .btn-cancel:hover {
      color: #40a9ff;
      border-color: #40a9ff;
    }

    .btn-confirm {
      border: none;
      background: #ff4d4f;
      color: white;
    }

    .btn-confirm:hover {
      background: #ff7875;
    }

    .advanced-search-sidebar {
      position: fixed;
      top: 0;
      right: -480px;
      width: 480px;
      height: 100vh;
      background: white;
      box-shadow: -4px 0 8px rgba(0, 0, 0, 0.1);
      transition: right 0.3s ease;
      z-index: 1000;
      display: flex;
      flex-direction: column;
    }

    .advanced-search-sidebar.show {
      right: 0;
    }

    .sidebar-overlay {
      position: fixed;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background-color: rgba(0, 0, 0, 0.5);
      z-index: 999;
    }

    .sidebar-header {
      padding: 20px;
      border-bottom: 1px solid #f0f0f0;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .sidebar-header h3 {
      margin: 0;
      font-size: 16px;
      font-weight: 500;
    }

    .close-button {
      background: none;
      border: none;
      font-size: 20px;
      color: #999;
      cursor: pointer;
    }

    .sidebar-body {
      flex: 1;
      padding: 20px;
      overflow-y: auto;
    }

    .form-group {
      margin-bottom: 20px;
    }

    .form-group label {
      display: block;
      margin-bottom: 8px;
      color: #262626;
    }

    .form-group input,
    .form-group select {
      width: 100%;
      height: 32px;
      padding: 4px 11px;
      border: 1px solid #d9d9d9;
      border-radius: 4px;
      transition: all 0.3s;
    }

    .form-group input:focus,
    .form-group select:focus {
      border-color: #40a9ff;
      box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
      outline: none;
    }

    .range-inputs {
      display: flex;
      align-items: center;
      gap: 8px;
    }

    .range-inputs input {
      width: calc(50% - 8px);
    }

    .range-inputs span {
      color: #999;
    }

    .sidebar-footer {
      padding: 20px;
      border-top: 1px solid #f0f0f0;
      display: flex;
      justify-content: flex-end;
      gap: 12px;
    }

    .btn-reset,
    .btn-cancel,
    .btn-search {
      padding: 8px 16px;
      border-radius: 4px;
      font-size: 14px;
      cursor: pointer;
      transition: all 0.3s;
    }

    .btn-reset {
      border: 1px solid #d9d9d9;
      background: white;
      color: #595959;
    }

    .btn-cancel {
      border: 1px solid #d9d9d9;
      background: white;
      color: #595959;
    }

    .btn-search {
      border: none;
      background: #1890ff;
      color: white;
    }

    .btn-reset:hover,
    .btn-cancel:hover {
      color: #40a9ff;
      border-color: #40a9ff;
    }

    .btn-search:hover {
      background: #40a9ff;
    }
  `],
  standalone: true,
  imports: [CommonModule, FormsModule, StorehouseFormComponent, StorehouseDetailComponent]
})
export class StorehouseComponent implements OnInit {
  // 查询条件
  searchParams = {
    warehouseCode: '',
    warehouseStatus: '',
    managementDept: '',
    warehouseManager: ''
  };

  // 表格数据
  warehouseList: Warehouse[] = [];
  selectedWarehouses: string[] = [];
  
  // 分页相关
  currentPage = 1;
  pageSize = 10;
  totalCount = 0;
  totalPages = 1;
  pages: number[] = [];
  hasMorePages = false;

  // 加载状态
  loading = false;

  // Form dialog properties
  showForm = false;
  isEditing = false;
  editingWarehouse?: WarehouseWithLocations;

  userNames: { [key: string]: string } = {};

  showDeleteConfirm = false;
  deletingWarehouseId: string | null = null;

  showAdvancedSearch = false;
  advancedSearchParams = {
    warehouseCode: '',
    warehouseName: '',
    minCapacity: null,
    maxCapacity: null,
    managementDept: '',
    warehouseManager: '',
    warehouseAddress: '',
    warehouseStatus: '',
    minLocationCount: null,
    maxLocationCount: null,
    operator: '',
    operationTimeStart: null,
    operationTimeEnd: null
  };

  showDetail = false;
  viewingWarehouse?: Warehouse;
  viewingLocations?: Location[];

  constructor(
    private storehouseService: StorehouseService,
    private toaster: ToasterService,
    private configState: ConfigStateService
  ) {}

  ngOnInit() {
    this.selectedWarehouses = [];
    this.loadWarehouseData();
  }

  // 加载仓库数据
  loadWarehouseData() {
    this.loading = true;
    const params = {
      skipCount: (this.currentPage - 1) * this.pageSize,
      maxResultCount: this.pageSize,
      ...this.searchParams
    };
    
    this.storehouseService.getList(params)
      .subscribe({
        next: (response) => {
          this.warehouseList = response.items;
          this.totalCount = response.totalCount;
          this.calculatePagination();
          // 获取所有创建者的用户名
          this.loadUserNames();
          this.loading = false;
        },
        error: (error) => {
          console.error('Failed to load warehouse data:', error);
          this.toaster.error('加载仓库数据失败，请稍后重试', '错误');
          this.loading = false;
        }
      });
  }

  // 加载用户名称
  loadUserNames() {
    const currentUser = this.configState.getOne('currentUser');
    if (currentUser) {
      this.userNames[currentUser.id] = currentUser.userName;
    }

    // 对于其他用户，暂时显示 ID
    this.warehouseList.forEach(warehouse => {
      if (warehouse.creatorId && !this.userNames[warehouse.creatorId]) {
        this.userNames[warehouse.creatorId] = warehouse.creatorId;
      }
    });
  }

  // 获取用户名称
  getUserName(userId: string): string {
    return this.userNames[userId] || userId || '-';
  }

  // 计算分页
  calculatePagination() {
    this.totalPages = Math.ceil(this.totalCount / this.pageSize);
    this.pages = [];
    
    if (this.totalPages <= 7) {
      for (let i = 1; i <= this.totalPages; i++) {
        this.pages.push(i);
      }
      this.hasMorePages = false;
    } else {
      if (this.currentPage <= 3) {
        this.pages = [1, 2, 3, 4, 5];
        this.hasMorePages = true;
      } else if (this.currentPage >= this.totalPages - 2) {
        this.pages = [
          this.totalPages - 4,
          this.totalPages - 3,
          this.totalPages - 2,
          this.totalPages - 1,
          this.totalPages
        ];
        this.hasMorePages = true;
      } else {
        this.pages = [
          this.currentPage - 2,
          this.currentPage - 1,
          this.currentPage,
          this.currentPage + 1,
          this.currentPage + 2
        ];
        this.hasMorePages = true;
      }
    }
  }

  // 修改搜索方法
  search(event?: Event) {
    if (event) {
      event.preventDefault();
    }
    
    this.currentPage = 1;
    this.loading = true;
    
    const params: any = {
      skipCount: (this.currentPage - 1) * this.pageSize,
      maxResultCount: this.pageSize,
      ...this.searchParams
    };

    console.log('Search params:', params);
    
    this.storehouseService.getList(params)
      .subscribe({
        next: (response) => {
          console.log('Search response:', response);
          this.warehouseList = response.items;
          this.totalCount = response.totalCount;
          this.calculatePagination();
          this.loadUserNames();
          this.loading = false;
        },
        error: (error) => {
          console.error('Failed to load warehouse data:', error);
          this.toaster.error('加载仓库数据失败，请稍后重试', '错误');
          this.loading = false;
        }
      });
  }

  // 修改重置方法
  reset(event?: Event) {
    if (event) {
      event.preventDefault();
    }
    
    this.searchParams = {
      warehouseCode: '',
      warehouseStatus: '',
      managementDept: '',
      warehouseManager: ''
    };
    this.currentPage = 1;
    this.loadWarehouseData();
  }

  // 页码变化
  goToPage(page: number) {
    if (page !== this.currentPage && page > 0 && page <= this.totalPages) {
      this.currentPage = page;
      this.loadWarehouseData();
    }
  }

  // 每页条数变化
  onPageSizeChange() {
    this.currentPage = 1;
    this.loadWarehouseData();
  }

  // 选择相关方法
  isSelected(id: string): boolean {
    return this.selectedWarehouses.includes(id);
  }

  toggleSelect(id: string) {
    const index = this.selectedWarehouses.indexOf(id);
    if (index === -1) {
      this.selectedWarehouses.push(id);
    } else {
      this.selectedWarehouses.splice(index, 1);
    }
  }

  isAllSelected(): boolean {
    return this.warehouseList.length > 0 && 
           this.selectedWarehouses.length === this.warehouseList.length;
  }

  toggleSelectAll() {
    if (this.isAllSelected()) {
      this.selectedWarehouses = [];
    } else {
      this.selectedWarehouses = this.warehouseList.map(w => w.id);
    }
  }

  // 新增仓库
  addWarehouse() {
    this.isEditing = false;
    this.editingWarehouse = undefined;  // 清空编辑数据
    this.showForm = true;
  }

  // 编辑仓库
  editWarehouse(warehouse: Warehouse) {
    console.log('Starting edit warehouse:', warehouse);
    this.isEditing = true;
    this.loading = true;
    
    // 获取完整的仓库信息，包括库位
    this.storehouseService.getById(warehouse.id)
      .pipe(finalize(() => this.loading = false))
      .subscribe({
        next: (response: any) => {
          console.log('Fetched warehouse data for editing:', response);
          
          // 从响应中获取数据
          const data = response.storehouse || response;
          const locations = response.locations || data.locations || [];
          
          // 构造仓库数据
          const storehouseData: Warehouse = {
            id: warehouse.id,
            warehouseCode: data.warehouseCode || warehouse.warehouseCode || '',
            warehouseName: data.warehouseName || warehouse.warehouseName || '',
            warehouseCapacity: Number(data.warehouseCapacity) || Number(warehouse.warehouseCapacity) || 0,
            warehouseAddress: data.warehouseAddress || warehouse.warehouseAddress || '',
            managementDept: data.managementDept || warehouse.managementDept || '',
            warehouseManager: data.warehouseManager || warehouse.warehouseManager || '',
            phone: data.phone || warehouse.phone || '',
            sort: data.sort || warehouse.sort || '0',
            warehouseStatus: data.warehouseStatus || warehouse.warehouseStatus || '启用',
            remarks: data.remarks || warehouse.remarks || '',
            locationCount: Number(data.locationCount) || Number(warehouse.locationCount) || 0,
            isLocked: Boolean(data.isLocked) || Boolean(warehouse.isLocked) || false,
            creatorId: data.creatorId || warehouse.creatorId,  // 可选字段，不需要默认值
            creationTime: data.creationTime || warehouse.creationTime,  // 可选字段，不需要默认值
            locations: locations
          };

          // 构造编辑数据
          this.editingWarehouse = {
            id: warehouse.id,  // 添加id字段
            storehouse: storehouseData,
            locations: locations.map((loc: any) => ({
              locationId: loc.locationId || '',
              locationName: loc.locationName || '',
              capacity: Number(loc.capacity) || 0,
              supervisor: loc.supervisor || '',
              status: Number(loc.status) || 0,
              sortOrder: Number(loc.sortOrder) || 0,
              remarks: loc.remarks || '',
              warehouseId: warehouse.id
            }))
          };
          
          console.log('Prepared editing data:', this.editingWarehouse);
          this.showForm = true;
        },
        error: (error) => {
          console.error('Failed to fetch warehouse details:', error);
          this.toaster.error('获取仓库详情失败，请重试', '错误');
        }
      });
  }

  // 隐藏表单
  hideForm() {
    this.showForm = false;
    this.isEditing = false;
    this.editingWarehouse = undefined;  // 清空编辑数据
  }

  // 处理表单提交
  handleFormSubmit(formData: WarehouseWithLocations) {
    if (this.isEditing) {
      const warehouseId = this.editingWarehouse?.storehouse.id || '';
      this.storehouseService.update(warehouseId, formData).subscribe({
        next: () => {
          this.toaster.success('修改成功');
          this.loadWarehouseData();
          this.showForm = false;
          this.isEditing = false;
          this.editingWarehouse = undefined;  // 清空编辑数据
        },
        error: (error) => {
          console.error('修改失败:', error);
          this.toaster.error('修改失败');
        }
      });
    } else {
      this.storehouseService.create(formData).subscribe({
        next: () => {
          this.toaster.success('添加成功');
          this.loadWarehouseData();
          this.showForm = false;
          this.editingWarehouse = undefined;  // 清空编辑数据
        },
        error: (error) => {
          console.error('添加失败:', error);
          this.toaster.error('添加失败');
        }
      });
    }
  }

  // 显示删除确认框
  deleteWarehouse(id: string) {
    this.deletingWarehouseId = id;
    this.showDeleteConfirm = true;
  }

  // 取消删除
  cancelDelete() {
    this.showDeleteConfirm = false;
    this.deletingWarehouseId = null;
  }

  // 确认删除
  confirmDelete() {
    if (this.deletingWarehouseId) {
      // 新增：删除前判断是否锁定
      const warehouse = this.warehouseList.find(w => w.id === this.deletingWarehouseId);
      if (warehouse && warehouse.warehouseStatus === '锁定') {
        this.toaster.error('该仓库已锁定，请先解除锁定');
        this.showDeleteConfirm = false;
        this.deletingWarehouseId = null;
        return;
      }
      this.loading = true;
      this.storehouseService.delete(this.deletingWarehouseId)
        .pipe(finalize(() => {
          this.loading = false;
          this.showDeleteConfirm = false;
        }))
        .subscribe({
          next: () => {
            this.toaster.success('删除成功');
            this.deletingWarehouseId = null;
            this.loadWarehouseData();
          },
          error: (error) => {
            console.error('Failed to delete warehouse:', error);
            this.toaster.error(error.error?.message || '删除失败，请稍后重试');
          }
        });
    }
  }

  // 批量删除选中的仓库
  deleteSelected() {
    if (!this.selectedWarehouses || this.selectedWarehouses.length === 0) {
      this.toaster.warn('请先勾选要删除的仓库');
      return;
    }
    this.deletingWarehouseId = null;  // 清空单个删除的ID
    this.showDeleteConfirm = true;
  }

  // 确认删除（批量或单个）
  confirmDeleteSelected() {
    // 如果是单个删除
    if (this.deletingWarehouseId) {
      this.confirmDelete();
      return;
    }

    // 批量删除
    if (this.selectedWarehouses.length === 0) {
      this.toaster.warn('请先勾选要删除的仓库');
      return;
    }

    // 检查是否有锁定的仓库
    const lockedWarehouses = this.warehouseList
      .filter(w => this.selectedWarehouses.includes(w.id))
      .filter(w => w.warehouseStatus === '锁定');

    if (lockedWarehouses.length > 0) {
      this.toaster.warn('选中的仓库中包含已锁定的仓库，请先解除锁定');
      this.showDeleteConfirm = false;
      return;
    }

    this.loading = true;
    this.storehouseService.batchDelete(this.selectedWarehouses)
      .pipe(finalize(() => {
        this.loading = false;
        this.showDeleteConfirm = false;
      }))
      .subscribe({
        next: () => {
          this.toaster.success('删除成功');
          this.selectedWarehouses = [];
          this.loadWarehouseData();
        },
        error: (error) => {
          if (error.error?.message?.includes('锁定')) {
            this.toaster.warn('选中的仓库中包含已锁定的仓库，请先解除锁定');
          } else {
            this.toaster.error(error.error?.message || '删除失败，请稍后重试');
          }
        }
      });
  }

  // 启用仓库
  enableSelected(event?: Event) {
    if (event) {
      event.preventDefault();
    }
    
    if (!this.selectedWarehouses || this.selectedWarehouses.length === 0) {
      this.toaster.warn('请先选择仓库');
      return;
    }

    // 检查选中的仓库状态
    const selectedWarehouse = this.warehouseList.find(w => w.id === this.selectedWarehouses[0]);
    if (selectedWarehouse?.warehouseStatus === '锁定') {
      this.toaster.warn('该仓库已锁定，请先解除锁定后再启用');
      return;
    }

    this.loading = true;
    const id = this.selectedWarehouses[0];
    
    this.storehouseService.updateStatus(id, '启用')
      .pipe(finalize(() => this.loading = false))
      .subscribe({
        next: () => {
          this.toaster.success('启用成功');
          this.selectedWarehouses = [];
          this.loadWarehouseData();
        },
        error: (error) => {
          console.error('Failed to enable warehouse:', error);
          if (error.error?.message?.includes('锁定')) {
            this.toaster.warn('该仓库已锁定，请先解除锁定后再启用');
          } else {
            this.toaster.error(error.error?.message || '启用失败，请稍后重试');
          }
        }
      });
  }

  // 停用仓库
  disableSelected(event?: Event) {
    if (event) {
      event.preventDefault();
    }
    
    if (!this.selectedWarehouses || this.selectedWarehouses.length === 0) {
      this.toaster.warn('请先选择仓库');
      return;
    }

    this.loading = true;
    const id = this.selectedWarehouses[0];
    
    this.storehouseService.updateStatus(id, '停用')
      .pipe(finalize(() => this.loading = false))
      .subscribe({
        next: () => {
          this.toaster.success('停用成功');
          this.selectedWarehouses = [];
          this.loadWarehouseData();
        },
        error: (error) => {
          console.error('Failed to disable warehouse:', error);
          this.toaster.error(error.error?.message || '停用失败，请稍后重试');
        }
      });
  }

  // 锁定仓库
  lockSelected(event?: Event) {
    if (event) {
      event.preventDefault();
    }
    
    if (!this.selectedWarehouses || this.selectedWarehouses.length === 0) {
      this.toaster.warn('请先选择仓库');
      return;
    }

    this.loading = true;
    const id = this.selectedWarehouses[0];
    
    this.storehouseService.updateStatus(id, '锁定')
      .pipe(finalize(() => this.loading = false))
      .subscribe({
        next: () => {
          this.toaster.success('锁定成功');
          this.selectedWarehouses = [];
          this.loadWarehouseData();
        },
        error: (error) => {
          console.error('Failed to lock warehouse:', error);
          this.toaster.error(error.error?.message || '锁定失败，请稍后重试');
        }
      });
  }

  // 切换高级搜索显示状态
  toggleAdvancedSearch() {
    this.showAdvancedSearch = !this.showAdvancedSearch;
  }

  // 修改高级搜索方法
  searchWithAdvanced(event?: Event) {
    if (event) {
      event.preventDefault();
    }
    
    this.currentPage = 1;
    this.loading = true;
    
    const params: any = {
      skipCount: (this.currentPage - 1) * this.pageSize,
      maxResultCount: this.pageSize,
      ...this.advancedSearchParams
    };

    console.log('Advanced search params:', params);

    this.storehouseService.getList(params)
      .subscribe({
        next: (response) => {
          console.log('Advanced search response:', response);
          this.warehouseList = response.items;
          this.totalCount = response.totalCount;
          this.calculatePagination();
          this.loadUserNames();
          this.loading = false;
          this.showAdvancedSearch = false; // 搜索后关闭侧边栏
        },
        error: (error) => {
          console.error('Failed to load warehouse data:', error);
          this.toaster.error('加载仓库数据失败，请稍后重试', '错误');
          this.loading = false;
        }
      });
  }

  // 修改高级搜索重置方法
  resetAdvancedSearch(event?: Event) {
    if (event) {
      event.preventDefault();
    }
    
    this.advancedSearchParams = {
      warehouseCode: '',
      warehouseName: '',
      minCapacity: null,
      maxCapacity: null,
      managementDept: '',
      warehouseManager: '',
      warehouseAddress: '',
      warehouseStatus: '',
      minLocationCount: null,
      maxLocationCount: null,
      operator: '',
      operationTimeStart: null,
      operationTimeEnd: null
    };
    this.searchWithAdvanced();
  }

  viewWarehouseDetails(warehouse: Warehouse) {
    this.loading = true;
    this.storehouseService.getById(warehouse.id)
      .pipe(finalize(() => this.loading = false))
      .subscribe({
        next: (response) => {
          this.viewingWarehouse = response.storehouse;
          this.viewingLocations = response.locations;
          this.showDetail = true;
        },
        error: (error) => {
          console.error('Failed to load warehouse details:', error);
          this.toaster.error('获取仓库详情失败，请重试', '错误');
        }
      });
  }

  hideDetail() {
    this.showDetail = false;
    this.viewingWarehouse = undefined;
    this.viewingLocations = undefined;
  }
} 